/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package wap.rockvilletech.util;

import java.io.*;

/**
 * 
 * @author Tasnim
 */
public class RootDirectory {
	
	private static final String fileSeparator = System.getProperty("file.separator");

	public static String getDirectory(Object obj) throws FileNotFoundException {
		String dirString = "";
		ClassLoader loader = obj.getClass().getClassLoader();
		String className = obj.getClass().getName();
		return getDirectoryFrom_Loader_ClassName(className, loader);
	}

	public static String getDirectory(String strClassName)
			throws FileNotFoundException {
		// System.out.println("strClassName: "+strClassName);
		String dirString = "";
		ClassLoader loader = ClassLoader.getSystemClassLoader();
		String className = strClassName;
		return getDirectoryFrom_Loader_ClassName(className, loader);
	}

	private static String getDirectoryFrom_Loader_ClassName(String className, ClassLoader loader) {
		String dirString = "";
		String classFileName = className.replace('.', '/') + ".class";
		java.net.URL url = loader.getResource(classFileName);
		String protocol = url.getProtocol();
		// System.out.println("protocol: "+protocol);
		if (protocol.equals("file")) {
			classFileName = className.replace('.', fileSeparator.charAt(0))+ ".class";
			File classFile = new File(url.getFile());
			String classFilePath = classFile.getPath();
			// System.out.println("classFilePath: "+classFilePath);
			// dirString = classFilePath.substring(0,
			// classFilePath.lastIndexOf(classFileName));
			dirString = classFilePath.substring(0, classFilePath.lastIndexOf(fileSeparator));
		} else if (protocol.equals("jar")) {
			File classFile = new File(url.getFile());
			String classFilePath = classFile.getPath();
			dirString = classFilePath.substring(0, classFilePath.lastIndexOf(".jar!"));
			int s;
			if (fileSeparator.charAt(0) == '/') {
				s = 5;
			} else {
				s = 6;
			}
			int l = dirString.lastIndexOf(fileSeparator.charAt(0)) + 1;
			dirString = dirString.substring(s, l);
		}
		// System.out.println("dirString: "+dirString);
		dirString = dirString.replaceAll("%20", " ");
		return dirString;

	}

}
